package com.weiyuwqj.app.web;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class SessionFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;
    HttpSession session = request.getSession();
    Object userIdObj = session.getAttribute("userId");
    String path = request.getServletPath();

    String[] noNeedLoginPaths = {"/admin/login"};
    String[] needLoginPaths = {"/admin"};

    boolean noNeedLogin = isMatch(path, noNeedLoginPaths);

     if(noNeedLogin){
        chain.doFilter(req, res);
      }else{
        boolean needLogin = isMatch(path, needLoginPaths);
        if(needLogin && userIdObj == null){
          response.sendRedirect("/login");
        }else{
          chain.doFilter(req, res);
        }
      }

  }

  public void init(FilterConfig filterConfig) {}

  public void destroy() {}

  private boolean isMatch(String path, String[] paths){
    boolean isMatch = false;
    for(String p:paths){
      if(path.startsWith(p)){
        isMatch = true;
        break;
      }
    }
    return isMatch;
  }

}